package com.example.sys.wx.config;

import com.example.sys.wx.handler.UserScanMessageHandler;
import com.example.sys.wx.handler.UserSendMessageHandler;
import com.example.sys.wx.handler.UserSubEventHandler;
import com.example.sys.wx.handler.UserUnSubEventHandler;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class WechatOpenConfig {

    @Resource
    private WechatOpenProperties wechatOpenProperties;

    @Bean
    public WxMpService wxMpService() {
        WxMpServiceImpl wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl storage = new WxMpDefaultConfigImpl();
        storage.setAppId(wechatOpenProperties.getAppId());
        storage.setSecret(wechatOpenProperties.getSecret());
        storage.setAesKey(wechatOpenProperties.getAesKey());
        storage.setToken(wechatOpenProperties.getToken());
        return storage;
    }

    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService, UserSendMessageHandler userSendMessageHandler, UserSubEventHandler userSubEventHandler, UserScanMessageHandler userScanMessageHandler, UserUnSubEventHandler userUnSubEventHandler) {
        WxMpMessageRouter wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
        //
        wxMpMessageRouter.setMessageDuplicateChecker(new WxMessageInMemoryDuplicateChecker());

        //发送消息事件
        wxMpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.TEXT).handler(userSendMessageHandler).end();

        //扫码事件
        wxMpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SCAN).handler(userScanMessageHandler).end();

        //关注事件
        wxMpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SUBSCRIBE).handler(userSubEventHandler).end();

        //取消关注事件
        wxMpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.UNSUBSCRIBE).handler(userUnSubEventHandler).end();

        return wxMpMessageRouter;
    }
}
